package cn.com.jslh.boarpro.util.template;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.com.jslh.boarpro.base.BaseApplication;
import cn.com.jslh.boarpro.main.view.fragment.AddTemplateFragment;
import cn.com.jslh.boarpro.util.WebService;
import cn.com.jslh.boarpro.util.database.DBHelper;
import cn.com.jslh.boarpro.util.database.DataBaseUtil;

/**
 * Created by Administrator on 2017/11/22.
 */

public class TemplateHelper {

    /**
     * 请求网络信息
     *
     * @param context
     * @param method
     * @param space
     * @param jsonObject
     * @param netSuccessListener
     */
    public static void getDatas(Context context, String method, String space, JSONObject jsonObject, WebService.NetSuccessListener netSuccessListener) {
        new WebService.Builder(context, method, space)
                .addProperty("jsonString", jsonObject.toString())
                .success(netSuccessListener)
                .showDialog(true)
                .post();
    }

    /**
     * 更新Item数据到数据库中
     *
     * @param context
     * @param addTempBaseItem
     */
    public static void updataItems(Context context, AddTempBaseItem addTempBaseItem) {
        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("result", addTempBaseItem.getResult());
        contentValues.put("placeholder", addTempBaseItem.getPlaceholder());
        contentValues.put("showInfo", addTempBaseItem.getShowInfo());
        sqLiteDatabase.update(AddTempBaseItem.class.getSimpleName(), contentValues,
                "title = ? and key = ?",
                new String[]{addTempBaseItem.getTitle(), addTempBaseItem.getKey()}
        );
        sqLiteDatabase.close();
        dbHelper.close();
    }

    /**
     * 事件处理
     *
     * @param context
     * @param actionName
     * @param netSuccessListener
     */
    public static void doAction(Context context, String actionName, WebService.NetSuccessListener netSuccessListener) {
        doAction(context, actionName, "", "", netSuccessListener);
    }

    public static void doAction(Context context, String actionName, String data, String keyid, WebService.NetSuccessListener netSuccessListener) {
        final JSONObject jsonObject = new JSONObject();
        BaseAction baseAction = null;
        try {
            baseAction = (BaseAction) DataBaseUtil.GetOneData(context, BaseAction.class, " where actionName = '" + actionName + "'");
            if(baseAction==null) {
                Toast.makeText(context, "配置错误，尚未配置" + actionName + "方法", Toast.LENGTH_SHORT).show();
                return;
            }
            if(!keyid.equals("")){
                jsonObject.put(keyid,data);
            }
            if(baseAction.getPostKeys()!=null) {
                JSONArray keys = new JSONArray(baseAction.getPostKeys());
                for (int i = 0; i < keys.length(); i++) {
                    String pkey = keys.get(i).toString();
                    switch (pkey) {
                        case "pageid":
                            jsonObject.put(pkey, SPUtils.getInstance().getString(BaseApplication.MODULETYPE));
                            break;
                        case "lineid":
                            jsonObject.put(pkey, SPUtils.getInstance().getString(BaseApplication.FLINEID));
                            break;
                        case "userid":
                            jsonObject.put(pkey, SPUtils.getInstance().getString(BaseApplication.FUSERID));
                            break;
                        case "content":
                            jsonObject.put(pkey, data);
                            break;
                        case "keyid":
                            jsonObject.put(pkey, keyid);
                            break;
                        default:
                            //从数据库中获取result
                            AddTempBaseItem addTempBaseItem = (AddTempBaseItem) DataBaseUtil.GetOneData(context,
                                    AddTempBaseItem.class,
                                    " where key = '" + pkey + "'");
                            if (addTempBaseItem != null) {
                                jsonObject.put(pkey, addTempBaseItem.getResult());
                            }
                            break;
                    }
                }
            }
            getDatas(context, baseAction.getActionName(), baseAction.getSpace(), jsonObject, netSuccessListener);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 刷新界面
     *
     * @param context
     */
    public static void doRefresh(Context context) {
        DataBaseUtil.excute(context, "UPDATE AddTempBaseItem set result ='' ,  showInfo = '' where iskeep = 0");
        AddTemplateFragment.notifyDatas();
    }

    public static boolean required(Context context) {
        //检查必填字段
        boolean reslut = false;
        try {
            JSONArray jsonArray = DataBaseUtil.GetData(context, "SELECT title from AddTempBaseItem WHERE isrequired =1 AND result =''");
            if (jsonArray.length() > 0) {
                reslut = true;
                String titles = "";
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = null;

                    jsonObject = jsonArray.getJSONObject(i);

                    String title = jsonObject.getString("title").replace("：", "");
                    String split = "，";
                    if (i == jsonArray.length() - 1) {
                        split = "";
                    }
                    titles = titles + title + split;
                }
                new AlertDialog.Builder(context)
                        .setTitle("提示")
                        .setMessage(titles + " 尚未录入")
                        .setPositiveButton("确定", null)
                        .show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return reslut;
    }
}
